import axios from "axios";
import { StorageSerializers, useStorage } from "@vueuse/core";
import { message } from "@/utils/resetMessage";
import { getFormData } from "@/utils/getFormData";

import router from "@/router/index";
axios.create({
    headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" },
});
//请求之前拦截
axios.interceptors.request.use(function (config) {
    console.log("request",config)
    return requestConfig(config);
}, function (error) {
    return Promise.reject(error);
});
//请求之后拦截
axios.interceptors.response.use(function (response) {
    return responseConfig(response);
}, function (error) {
    console.log(error)
    handleStatus(error)
    return Promise.reject(error);
});


//请求配置处理函数
const requestConfig = config => {
    const userInfo = useStorage("userInfo", null, sessionStorage, {
        serializer: StorageSerializers.object
    })
    if (userInfo.value && userInfo.value.token) {//登录之后接口添加token
        config.headers['Authorization'] = "Bearer " + userInfo.value.token;
    }
    if(config.method.toUpperCase()=="POST"&& !(config.data instanceof FormData)){//post提交参数处理成Form Data格式
        config.data = getFormData(config.data);
    }
    config.timeout=6000;
    console.log("requestConfig",config)
    return config;
}

//请求数据处理函数
const responseConfig = response => {
    if (response.data&&response.data.Status == "err") {
        message.error(response.data.Content);
    }
    return response.data;
}

const handleStatus = (error) => {
    console.log(error.response);
    switch (error.response.status) {
        case 401:
            message.error("登录过期请，重新登录！");
            router.push("/")
            break;
        case 500:
            message.error(error.response.data.Content);
            break;
        default :
            break;

    }
}
export default axios

